package com.yst.webplugin.pathhandler;

import com.yst.spring.context.SpringContext;
import com.yst.webplugin.api.ApiPathHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class PathHandlerUtils {

    private static final List<IPathHandler> pathHandlerList=new ArrayList<>();

    private static final Map<String,IPathHandler> cache=new ConcurrentHashMap<>();

    private static final SpringContext.IContextReady contextReady= context -> {
        pathHandlerList.add(new ApiPathHandler(context));
    };

    public static IPathHandler getHandler(String path){
        return cache.computeIfAbsent(path,(key)->{
            for(IPathHandler pathHandler:pathHandlerList){
                if (pathHandler.supports(key)){
                    return pathHandler;
                }
            }
            return null;
        });
    }
    public static void registerHandler(IPathHandler handler){
        if (!pathHandlerList.contains(handler)){
            pathHandlerList.add(handler);
        }
    }
    public static void unregisterHandler(IPathHandler handler){
        pathHandlerList.remove(handler);
    }

    static {
        SpringContext.addOnReadyListener(contextReady);
    }
}
